<template>
  <div class="app-container">
    <div class="filter-container">
      <k-button v-if="authorityHandle(56)" class="top-btn" value="创建红包" @click.native="creatBloodDialog" />
      <!-- <k-button class="top-btn" value="玩法介绍" @click.native="codeListDialog.showHide = true" /> -->
      <k-input
        v-model.trim="codeKey"
        class="filter-item"
        is-search
        placeholder="红包码或手机号"
        :search-fun="search"
        @keyup.enter.native="search"
      />
    </div>
    <!-- 创建 roll 房 -->

    <!--表格相关 -->
    <el-table
      :data="codeTableData"
      fit
      border
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
    >
      <el-table-column width="80px" type="index" label="序号" align="center" />
      <el-table-column prop="envelopeTheme" min-width="100px" label="红包主题" align="center" show-overflow-tooltip />
      <el-table-column min-width="80px" label="红包金额（F）" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.minEnvelopeAmount }} - {{ scope.row.maxEnvelopeAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="anchorName" min-width="80px" label="所属主播" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.fissionList" :key="index">
            <span>{{ item.anchorName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="creatorName" min-width="60px" label="创建人" align="center" show-overflow-tooltip />
      <el-table-column prop="envelopeNum" min-width="60px" sortable label="红包个数" align="center" show-overflow-tooltip :formatter="formatter" />
      <el-table-column min-width="80px" label="参与条件" align="center">
        <template slot-scope="scope">
          期间消费 {{ scope.row.rechargeTotal }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" min-width="80px" sortable label="创建时间" align="center" show-overflow-tooltip />
      <el-table-column min-width="170px" label="有效时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column min-width="80px" label="开关" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.openStatus"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="1"
            :disabled="!authorityHandle(56)"
            :inactive-value="2"
            @change="updateCodeStatus($event,scope)"
          />
        </template>
      </el-table-column>
      <el-table-column min-width="150px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="查看/修改" @click.native="updateCodeDialog(scope.row)" />
            <k-button class="table-btn" value="详情" @click.native="openCodeRedDetail(scope.row.id)" />
            <k-button
              v-if="authorityHandle(56)"
              class="table-btn"
              value="删除"
              :disabled="scope.row.openStatus===1?true:false"
              @click.native="deleteRedItem(scope.row.id)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 10"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />
    <!-- 创建红包 弹窗 -->

    <k-dialog
      :show-hide.sync="creatRollRoom.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(56)"
      :close-fun="handleCloseDialog"
      @click="saveCodeRed"
    >
      <div class="dialog_creatRollRoom">
        <el-form :model="codeRedInfo" label-width="auto">
          <el-form-item label="红包主题：">
            <el-input
              v-model="codeRedInfo.envelopeTheme"
              :readonly="!authorityHandle(56)"
              show-word-limit
              placeholder="请输入红包主题"
            />
          </el-form-item>
          <el-form-item label="红包金额（F）：">
            <el-input
              v-model="codeRedInfo.minEnvelopeAmount"
              :readonly="!authorityHandle(56)"
              class="red_money"
            />
            <i style="margin: 0 3px;"> — </i>
            <el-input
              v-model="codeRedInfo.maxEnvelopeAmount"
              :readonly="!authorityHandle(56)"
              class="red_money"
            />
          </el-form-item>

          <div class="code-list">
            <div v-for="(item,index) in codeRedInfo.fissionList" :key="index" class="code-item">
              <p>红包个数：</p><el-input v-model="item.fissionNum" :readonly="!authorityHandle(56)" onkeyup="value=value.replace(/[^0-9.]/g,'')" />
              <p>所属主播：</p>
              <!--  添加可以搜索 :disabled="value.disabled" @change="isDisabled()"-->
              <el-select v-model="item.fissionId" filterable :disabled="!authorityHandle(56)">
                <el-option v-for="value in belongList" :key="value.lineId" :label="value.lineName" :value="value.lineId" @click.native="JingcuiBalance(item,value,index)"/>
              </el-select>
              <div class="operation" style="margin:0 5px;" v-show="item.show">晶粹余额:{{item.price}}</div>
              <!-- <div class="operation">
                <i v-show="codeRedInfo.fissionList.length > 1" class="el-icon-error" style="font-size: 16px; cursor: pointer;" @click="cutItem(index)" />
                <i v-show="index == codeRedInfo.fissionList.length - 1" class="el-icon-circle-plus" style="font-size: 16px; color:#3b425d; cursor: pointer;" @click="addItem" />
              </div> -->
            </div>
          </div>

          <el-form-item label="期间消费(R)：">
            <el-input
              v-model="codeRedInfo.rechargeTotal"
              :readonly="!authorityHandle(56)"
              placeholder="请输入期间消费"
            />
          </el-form-item>
          <el-form-item label="有效时间：" style="width:300px">
            <el-date-picker
              v-model="timeCotinue"
              :disabled="!authorityHandle(56)"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="datetimerange"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
    <!-- 红包码 -->
    <k-dialog
      :show-hide.sync="codeListDialog.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="红包码"
      ok-btn-text="一键复制"
      :show-foot="false"
      :two-btn="true"
      class="btn_copykey"
      :data-clipboard-text="redCodeList.join('\n')"
      :close-fun="handleCopyCodeDialog"
      @click="onekeyCopyCode"
    >
      <div class="grid-div">
        <div v-for="(item ,index) in redCodeList" :key="index" class="item">{{ item }}</div>
      </div>
    </k-dialog>

    <!-- 搜索后列表 -->
    <k-dialog
      title="领取详情"
      :show-hide.sync="detailedShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="false"
    >
      <div class="detailedList">
        <el-table
          :data="detailedList"
          fit
          border
          highlight-current-row
          style="width: 100%;border-radius:8px;"
          :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
        >
          <el-table-column width="80px" type="index" label="序号" align="center" />
          <el-table-column
            prop="amount"
            min-width="100px"
            label="红包金额（F）"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="userMobile"
            min-width="100px"
            label="领取名用户名"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="anchorName"
            min-width="80px"
            label="所属主播"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="userName"
            min-width="80px"
            label="领取名昵称"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="receiveTime"
            min-width="80px"
            label="领取时间"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="receiveStatusName"
            min-width="80px"
            label="红包状态"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column prop="createTime" min-width="80px" sortable label="创建时间" align="center" show-overflow-tooltip />
          <el-table-column min-width="200px" label="生效时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.startTime }}-{{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="envelopePassword"
            min-width="80px"
            label="红包码"
            align="center"
            show-overflow-tooltip
          />
        </el-table>
      </div>
    </k-dialog>

  </div>
</template>
<script>
import {
  saveSingleData,
  listSingleData,
  updateSingleData,
  deleteSingleData,
  updateSingleStatus,
  listSingleItemDataByKey
} from '@/api/red/data'
import Pagination from '@/components/Pagination'
import ClipboardJS from 'clipboard'
import { getAnchors } from '@/api/user/user'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      giveType: 1,
      radioState: false,
      redMoneyFlag: false,
      maxMinFlag: true,
      dialogStatus: 'create',
      updateButtonState: false,
      textMap: {
        update: '修改红包',
        create: '创建红包'
      },
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '', // 排序 正向(asc)逆向(desc),
        startTime: undefined, // 饰品外观',
        endTime: undefined, // 饰品类别',
        key: '' // 箱子名称或关键词 箱子配置界面所用'
      },
      codeTableData: [],
      redCodeList: [],
      codeRedInfo: {
        id: undefined,
        envelopeTheme: undefined,
        envelopeIntroduce: undefined,
        envelopeNum: undefined,
        rechargeTotal: undefined,
        startTime: undefined,
        endTime: undefined,
        openStatus: undefined,
        maxEnvelopeAmount: undefined,
        minEnvelopeAmount: undefined,
        fissionList: [
          {
            fissionNum: undefined,
            fissionId: undefined
          }
        ]
      },
      timeValue: '',
      timeCotinue: [],
      conditions: {
        keyword: null
      },
      creatRollRoom: {
        showHide: false
      },
      codeListDialog: {
        showHide: false
      },
      ruleGuide: {
        showHide: false
      },

      codeKey: '',
      detailedShow: false,
      detailedList: [],
      belongList: [],
    }
  },
  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null
    }
  },
  created() {
    this.getAnchors()
    this.loadData()
  },
  methods: {
    JingcuiBalance(item,value,index){
      if (item.fissionId ==-1) {
        this.$set(item, "show", false);
        this.$set(item, "price", '');
      }else{
        this.$set(item, "show", true);
        this.$set(item, "price", value.price || 0);
      }
    },
    // 获取主播房间的创建人
    getAnchors() {
      this.belongList = []
      getAnchors({ 'queryType': 1 }).then(res => {
        let obj=   {
                "lineId": -1,
                "lineName": "全部玩家",
                "lineCheck": false,
                "roleId": null,
                "price": null
            }
        this.belongList.push(obj,...res.data.data)
      })
    },
    // 搜索
    search() {
      if (this.codeKey.trim() == '') {
        this.$message.error('请输入红包码或者手机号')
        return
      }
      listSingleItemDataByKey({
        key: this.codeKey
      }).then(res => {
        if (res.data.length > 0) {
          this.detailedList = res.data
          this.detailedShow = true
        } else {
          this.$message.error('暂无信息')
        }
      })
    },

    cutItem(index) {
      this.codeRedInfo.fissionList.splice(index, 1)
      this.isDisabled()
    },
    addItem() {
      this.codeRedInfo.fissionList.push({
        fissionNum: undefined,
        fissionId: undefined

      })
      this.isDisabled()
    },
    // 添加
    async isDisabled(val) {
      this.belongList.forEach((item, index) => {
        this.belongList[index].disabled = false
        this.codeRedInfo.fissionList.forEach(element => {
          if (item.lineId == element.fissionId) {
            this.belongList[index].disabled = true
          }
        })
      })
    },

    radioChange(v) {
      this.maxMinFlag = v === 1
      this.redMoneyFlag = v !== 1
    },
    loadData() {
      listSingleData(this.listQuery).then(res => {
        this.totalRows = res.data.totalRows
        this.codeTableData = res.data.rows
      })
    },
    // 肉房持续时间区间选择
    datetimerange(timeValue) {
      this.codeRedInfo.startTime = this.timeCotinue ? timeValue[0] : null
      this.codeRedInfo.endTime = this.timeCotinue ? timeValue[1] : null
    },

    creatBloodDialog() {
      this.$resetForm(this.codeRedInfo)
      this.timeCotinue = []
      this.codeRedInfo.fissionList = [
        {
          fissionNum: undefined,
          fissionId: undefined
        }
      ]
      this.dialogStatus = 'create'
      this.creatRollRoom.showHide = true
      this.updateButtonState = true
    },
    /**
     * 红包个数
     * @param {*} row
     */
    formatter(row) {
      if (!row.fissionList) return '异常'
      const arr = row.fissionList.reduce((arr, size) => { return arr + size.fissionNum }, 0) // 对附件的大小求和
      return arr
    },

    updateCodeDialog(row) {
      this.dialogStatus = 'update'
      this.updateButtonState = row.openStatus === 2
      this.creatRollRoom.showHide = true
      Object.assign(this.codeRedInfo, row)
      if (this.codeRedInfo.fissionList == null) {
        this.codeRedInfo.fissionList = [
          {
            fissionNum: undefined,
            fissionId: undefined
          }
        ]
      }
      this.timeCotinue = [row.startTime === null ? '' : row.startTime, row.endTime === null ? '' : row.endTime]
      this.isDisabled()
    },
    onekeyCopyCode() {
      const clipboard = new ClipboardJS('.btn_copykey')
      clipboard.on('success', e => {
        this.$message.success('复制成功')
        this.loadData()
        this.codeListDialog.showHide = false
        //  释放内存
        e.clearSelection()
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        this.$message.error('复制出错')
        clipboard.destroy()
      })
    },
    handleCopyCodeDialog() {
      this.loadData()
    },
    // 新增多码红包
    saveCodeRed() {
      if (!this.codeRedInfo.envelopeTheme) {
        this.$message.error('请输入红包主题')
        return
      }

      if (!this.codeRedInfo.minEnvelopeAmount || !this.codeRedInfo.maxEnvelopeAmount) {
        this.$message.error('请输入红包金额（F）')
        return
      }

      // if(this.codeRedInfo.rechargeTotal){
      // 	this.$message.error('请输入期间消费')
      // 	return
      // }

      if (!this.codeRedInfo.startTime || !this.codeRedInfo.endTime) {
        this.$message.error('请输入有效时间')
        return
      }

      if (this.codeRedInfo.fissionList.length == 0) {
        this.$message.error('请输入红包个数')
        return
      }
      const status = this.codeRedInfo.fissionList.every(item => item.fissionNum && item.fissionId)
      if (!status) {
        this.$message.error('红包个数与所属主播必填')
        return
      }
      console.log(this.codeRedInfo,'qqqq');

      if (this.dialogStatus === 'create') {
        saveSingleData(this.codeRedInfo).then(res => {
          if (res.data.success) {
            this.$message.success('保存成功')
            this.$resetForm(this.codeRedInfo)
            this.redCodeList = res.data.data
            this.codeListDialog.showHide = true
          } else {
            this.$message.error(res.data.msg)
          }
        })
      } else {
        updateSingleData(this.codeRedInfo).then(res => {
          if (res.data.success) {
            this.$message.success('修改成功')
            this.$resetForm(this.codeRedInfo)
            this.loadData()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
      this.handleCloseDialog()
    },

    handleCloseDialog() {
      this.creatRollRoom.showHide = false
    },
    deleteRedItem(id) {
      this.$confirm('确定删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSingleData({
          id
        }).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 打开多码红包详情
    openCodeRedDetail(id) {
      this.$router.push({
        path: '/redpockets/codepockets-detail',
        query: {
          id
        }
      })
    },
    // 更新红包状态
    updateCodeStatus(event, scope) {
      this.$log(scope.row.rollSwitch)
      updateSingleStatus({
        'id': scope.row.id
      }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 搜索查询事件
    handleFilter() {
      this.listQuery.pager.pageNo = 1
      this.loadData()
    }
  }

}
</script>
<style lang="scss" scoped>
	$menuText:#14162E; // 侧边栏字体颜色
	$hoverColor:#79BBFF; // 鼠标停留主色调浅色
	$mainColor:#3b425d; // 主色调

	.detailedList {
		width: 1400px;
		min-height: 300px;
	}

	.filter-container {
		width: 100%;
		height: 48px;
		line-height: 48px;
		margin-bottom: 50px;

		.filter-item {
			display: inline-block;
			vertical-align: middle;
			margin-bottom: 10px;
		}

		.kInput {
			position: absolute;
			right: 20px;
		}

		.filter-title {
			height: 48px;
			line-height: 48px;
			font-size: 16px;
			font-weight: 500;
			margin-right: 22px;
			color: #14162E;
		}

		.user-item {
			margin-left: 10px;
			margin-right: 20px;
		}

		.room-type,
		.user-status,
		.account-status {
			margin-right: 20px;
		}
	}

	.grid-div {
		display: grid;
		grid-template-columns: repeat(7, 120px);

		.item {
			height: 50px;
			font-size: 14px;
			line-height: 50px;
			text-align: center;
			border: 1px solid #E3E2E7;
			width: 120px;
			overflow: hidden;
			display: inline-block;
			text-overflow: ellipsis;
			white-space: nowrap;
			padding: 0 10px;
		}
	}

	.red_money {
		width: 200px;
	}

	.grid-div {
		display: grid;
		grid-template-columns: repeat(7, 120px);

		.item {
			height: 50px;
			font-size: 14px;
			line-height: 50px;
			text-align: center;
			border: 1px solid #E3E2E7;
			width: 120px;
			overflow: hidden;
			display: inline-block;
			text-overflow: ellipsis;
			white-space: nowrap;
			padding: 0 10px;
		}
	}

	.top-btn {
		margin: 30px 0px 30px 0px;
		font-size: 14px;
		color: #ffffff;

		&:nth-of-type(2) {
			margin-left: 10px;
		}
	}

	.kSelect .el-select .el-input .el-input__inner {
		width: 124px;
	}

	.code-list{
		margin-bottom: 16px;
		.code-item{
			display: flex;
			margin-bottom: 10px;
			p{
				font-size: 14px;
				font-weight: bold;
			}
			.el-input{
				width: 120px;
				margin:0 46px 0 10px;
			}
			.el-select{
				width: 180px;
				
			}
			.operation{
				min-width: 46px;
				display: flex;
				justify-content: space-between;
				align-items: center;

			}
		}
	}

	::v-deep .el-select .el-input.is-focus .el-input__inner {
		border-color: $mainColor;
	}

	::v-deep .el-input__inner:focus {
		border-color: $mainColor;
	}

	.el-form-item__label-wrap .el-form-item__label {
		float: none;
	}

	.dialog_creatRollRoom {
		display: flex;
		flex-direction: row;
		justify-content: center;
		margin: 40px 80px;

		::v-deep .el-select .el-select__tags>span {
			display: none;
		}

		::v-deep .el-range-editor.el-input__inner {
			width: 400px;
		}

		.el-tag+.el-tag {
			margin-left: 10px;
		}

		.el-tag {
			color: $mainColor;
			background-color: #ffffff;
			border-color: $mainColor;

			::v-deep .el-tag__close {
				color: $mainColor;
			}

			::v-deep .el-icon-close:hover {
				color: #ffffff;
				background: $mainColor;
			}
		}
	}

	.form-modify {
		display: flex;
		flex-direction: row;
		justify-content: center;
		margin: 10px 80px;
	}

	.editer {
		width: 500px;
		border-radius: 8px;
		float: left;
		box-sizing: border-box;
		color: #606266;

		::v-deep .ql-container {
			height: 270px;
			border-radius: 0px 0px 8px 8px;
		}

		::v-deep .ql-toolbar.ql-snow {
			border-radius: 8px 8px 0px 0px;
		}
	}

	.chargeform {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	::v-deep .el-switch__label.is-active {
		color: $mainColor;
	}

	.addBox_dialog {
		display: flex;
		flex-direction: column;
		justify-content: center;

		::v-deep .el-dialog__body {
			width: 678px;
			margin: 40px 80px;
		}

		::v-deep .el-select .el-select__tags>span {
			display: none;
		}

		.el-tag+.el-tag {
			margin-left: 10px;
		}

		.el-tag {
			color: $mainColor;
			background-color: #ffffff;
			border-color: $mainColor;

			::v-deep .el-tag__close {
				color: $mainColor;
			}

			::v-deep .el-icon-close:hover {
				color: #ffffff;
				background: $mainColor;
			}
		}
	}

	.cell-baby {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;

	}

	.ellipsis-span {
		width: 80px;
		overflow: hidden;
		display: inline-block;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>
